package com.example.springbean.transaction;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *  方法内的事务失败会影响父类的事务，一同回滚
 *  如果子事务抛异常，会将异常抛出了，外事务会感知到，所以会一起回滚
 *  如果catch 子事务，父类事务正常执行
 *  如果子事务开启一个新的事务，如果已经执行成功，父类异常 则不回滚
 *
 * @author 15871
 */
@Service
public class TestTransaction {


    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void a() {
        TestTransaction proxy = (TestTransaction) AopContext.currentProxy();
        try {
            proxy.b();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        int a = 10 / 0;
        User user = new User();
        user.setName("a");
        user.setPassword("zlx");
        user.setTel("1300000000");
        userMapper.insert(user);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void b() {
        int b = 10 / 0;
        User user = new User();
        user.setName("b");
        user.setPassword("zlx");
        user.setTel("1300000000");
        userMapper.insert(user);
    }


}
